// 引入 ws 模块
let WebSocketServer = require("ws").Server;
// 创建一个ws实例
let wss = new WebSocketServer({
    port: 9000
});
// 创建一个对象
let clientMap = new Object();
// 给每个进入的聊天者一个名字
var name = 0;
wss.on('connection', (ws) => {
    ws.name = name++;
    console.log(ws.name + "上线");
    clientMap[ws.name] = ws;
    ws.on('message', (message) => {
        broadcast(message, ws);
    });
    ws.on('close', () => {
        console.log("退出");
    });
});

function broadcast(msg, ws) {
    for (var key in clientMap) {
        clientMap[key].send(ws.name + '说：' + msg);
    }
}